<script setup>
import { ref, onMounted, computed } from 'vue'
import { sessionApi, pageKeywordsApi, saveKeywordApi, oneKeywordApi, proKeywordsApi } from '@/commons/api'
import routes from '@/commons/router'
import Msg from '@/components/message'
import confirm from '@/components/confirm'
import Pager from '@/components/pager/Pager.vue'
import { CScrollbar } from 'c-scrollbar'
import Loader from '@/components/loader/Loader.vue'

const kwKind = 2
const loadShow = ref(false)

// 界面挂载前处理
onMounted(() => {
  // 获取用户会话信息
  checkAuth()
})

let procAuth = {
  addAuth: false,
  delAuth: false,
  edtAuth: false,
  pasAuth: false,
  unpAuth: false
}
// checkAuth 获取权限
const checkAuth = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    if (res.code === import.meta.env.VITE_SUCCESS_CODE) {
      const userBtnCode = res.data.btnCodes
      procAuth = {
        addAuth: userBtnCode.indexOf('1002020001') !== -1,
        delAuth: userBtnCode.indexOf('1002020002') !== -1,
        edtAuth: userBtnCode.indexOf('1002020003') !== -1,
        pasAuth: userBtnCode.indexOf('1002020004') !== -1,
        unpAuth: userBtnCode.indexOf('1002020005') !== -1
      }
      await list(0, 1)
    } else {
      localStorage.removeItem("token")
      Msg({ kind: 'error', txt: res.msg })
      routes.replace('/login')
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const schRef = ref({
  keywords: '',
  kind: kwKind,
  offset: 0,
  limit: 20
})
const total = ref(0)
const curPage = ref(1)
const kwList = ref([])
const hasData = ref(false)
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageKeywordsApi(schRef.value)
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    hasData.value = true
    total.value = res.data.total
    kwList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    keywords: '',
    offset: 0,
    limit: 20
  }
  list(0, 1)
}

// 选择效果实现
const idList = ref([])
const checkList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    kwList.value.forEach(item => {
      idList.value.push(item.kwId)
      checkList.value.push(true)
    })
  } else {
    kwList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, roleId) => {
  if(!checkList.value[idx]) {
    idList.value.push(roleId)
  } else {
    idList.value.splice(idList.value.findIndex(id => id === roleId), 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const kwForm = ref({
  kwId: '',
  kind: kwKind,
  kwName: '',
  kwCount: ''
})
// add 新增
const showModal = ref(false)
const add = () => {
  showModal.value = true
}
// update 修改
const update = async (kwId) => {
  const res = await oneKeywordApi({ kwId })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    showModal.value = true
    kwForm.value = res.data
  } else {
    Msg({ kind: 'info', txt: '暂无内容' })
  }
}
// save 保存提交
const save = async () => {
  let kwName = kwForm.value.kwName
  let kwCount = kwForm.value.kwCount
  if(kwName === '' || kwName.length > 50) {
    Msg({ kind: 'warn', txt: '关键字名称不能为空，且长度不超过50个字符！' })
    return
  }
  kwForm.value.kwCount = parseInt(kwCount)
  loadShow.value = true
  try {
    const res = await saveKeywordApi(kwForm.value)
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      closeModal()
      await list(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，关键字保存成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  showModal.value = false
  kwForm.value = {
    kwId: '',
    kind: kwKind,
    kwName: '',
    kwCount: ''
  }
}

// deletes 删除关键字
const deletes = async() => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作处理！' })
    return
  }
  confirm('确定要处理选中的数据吗？').then(() => {
    proKeywords()
  }).catch(() => {
    Msg({ kind: 'info', txt: "您取消了处理选中数据的操作~！" })
  })
}
// proKeywords 删除关键字实现，分离出来防止调用时异步报错
const proKeywords = async () => {
  let kwIds = idList.value.join(',')
  loadShow.value = true
  try {
    const res = await proKeywordsApi({ kwIds })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      await list(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，关键字处理成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// fmtState 状态转码
const fmtState = computed(() => {
  return (states) => {
    let str
    switch (states) {
      case 1:
        str = '已启用'
        break;
      case 3:
        str = '已停用'
        break;
      default:
        str = '其它'
        break
    }
    return str
  }
})
</script>

<template>
  <div class="a">
    <div class="b">
      <div class="c">
        <div v-if="procAuth.addAuth" class="btn-pi mr15" title="新增" @click="add"><i class="iconfont">&#xea2d;</i> 新增</div>
        <div v-if="procAuth.delAuth" class="btn-de mr15" title="删除" @click="deletes"><i class="iconfont">&#xea45;</i> 删除</div>
        <div class="btn-r mr15" title="筛选" @click="search"><i class="iconfont">&#xea49;</i></div>
        <div class="btn-r mr15" title="刷新" @click="list(0, 1)"><i class="iconfont">&#xea8c;</i></div>
      </div>
      <div class="d"><i class="iconfont">&#xeaaa;</i> 当前位置：工作台 > 资讯管理 > 关键字</div>
    </div>
    <div v-show="schShow" class="e">
      <div class="mr15"><input type="text" v-model="schRef.keywords" maxlength="30" placeholder="请输入关键字" class="f" /></div>
      <div class="btn-pi mr15" title="搜索" @click="list(0, 1)"><i class="iconfont">&#xea8e;</i> 搜索</div>
      <div class="btn-d" title="重置" @click="clrSch"><i class="iconfont">&#xea4f;</i> 重置</div>
    </div>
    <div v-if="hasData">
      <table>
        <tbody>
        <tr>
          <th style="width: 5%;"><span @click="checkAll()" title="全选"><i :class="['iconfont', allCheck ? 'chked' : 'chk']" v-html="allCheck ? '&#xea3a;' : '&#xea46;'" /></span></th>
          <th style="width: 20%;">名称</th>
          <th style="width: 15%;">次数</th>
          <th style="width: 20%;">种类</th>
          <th style="width: 10%;">操作</th>
        </tr>
        <tr v-for="(curKw, index) in kwList" :key="curKw.kwId" class="tr-style">
          <td class="txt-center"><span @click="checkCurId(index, curKw.kwId)" title="选择"><i :class="['iconfont', checkList[index] ? 'chked' : 'chk']" v-html="checkList[index]  ? '&#xe685;' : '&#xe686;'" /></span></td>
          <td class="txt-center">{{curKw.kwName}}</td>
          <td class="txt-center">{{curKw.kwCount}}</td>
          <td class="txt-center"><span :class="[curKw.kind===1 ? 'tag-s' : 'tag-e']">{{curKw.kind===1 ? '用户搜索' : '关键字'}}</span></td>
          <td class="txt-center">
            <span v-if="procAuth.edtAuth" class="cl-warn" title="修改" @click="update(curKw.kwId)"><i class="iconfont">&#xea48;</i> 修 改</span>
          </td>
        </tr>
        </tbody>
      </table>
      <pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 600px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 保存关键字信息</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont fs22">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>关键字名称</div>
                <div><input type="text" v-model="kwForm.kwName" maxlength="50" placeholder="关键字" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>搜索次数</div>
                <div><input type="text" v-model="kwForm.kwCount" maxlength="9" placeholder="请输入搜索次数" class="ipt" /></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-pi mr15" @click="save"><i class="iconfont">&#xea90;</i> 保存</div>
              <div class="btn-d" @click="closeModal"><i class="iconfont">&#xea4f;</i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.a {padding: 10px;}
.b {padding: 0 20px 10px 20px; display: flex; display: -webkit-flex;}
.c {display: inline-flex; display: -webkit-inline-flex;}
.d {flex-grow: 1; text-align: right; padding-top: 10px; color: #666;}
.e {border: 1px dashed #DDD; padding: 15px; display: flex; display: -webkit-flex; margin-bottom: 10px;}
.f {width: 240px; height: 28px; padding-left: 10px;}
.f:focus {border: 1px solid #66B1FF; outline: none;}
</style>